var geoserverUrl = 'http://127.0.0.1:8180/geoserver/osm_ws';
var activeShapePoints = [];
var activeShape;
var floatingPoint;
//绘制geojson图层样式
var geoJsonStyle = {
    stroke: Cesium.Color.YELLOW,
    strokeWidth: 3,
    fill: Cesium.Color.YELLOW.withAlpha(0.1)
};
var highlightFace = null;
var readyforPick=false;

function axToolIdentity(layer){
    drawingMode = "polygon";
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    //窗口事件句柄
    if(handler==null){
        handler=new  Cesium.ScreenSpaceEventHandler(viewer.canvas);
    }
    handler.setInputAction(function (event) {
        const ray = viewer.camera.getPickRay(event.position);//根据鼠标点击坐标和相机坐标构建射线
        const earthPosition = viewer.scene.globe.pick(ray, viewer.scene);//射线与球面求交，在地面的交点
        // `earthPosition` will be undefined if our mouse is not over the globe.
        if (Cesium.defined(earthPosition)) //鼠标点击在地球范围内
        {
            if (activeShapePoints.length === 0) {
                floatingPoint = createPoint(earthPosition);
                activeShapePoints.push(earthPosition);
                const dynamicPositions = new Cesium.CallbackProperty(function () {
                    if (drawingMode === "polygon") {
                        return new Cesium.PolygonHierarchy(activeShapePoints);
                    }
                    return activeShapePoints;
                }, false);//回调函数
                activeShape = drawShape(dynamicPositions);
            }
            activeShapePoints.push(earthPosition);
        // createPoint(earthPosition);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);//鼠标左键

    handler.setInputAction(function (event) {
        if (Cesium.defined(floatingPoint)) {
            const ray = viewer.camera.getPickRay(event.endPosition);
            const newPosition = viewer.scene.globe.pick(ray, viewer.scene);
            if (Cesium.defined(newPosition)) {
                floatingPoint.position.setValue(newPosition);
                activeShapePoints.pop();
                activeShapePoints.push(newPosition);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);//鼠标移动

    handler.setInputAction(function (event) {    
        var polygon = drawShape(activeShapePoints);
        var extent =getExtentByCartesian3(activeShapePoints);   
        viewer.entities.remove(polygon);
        terminateShape();
        drawingMode = "unknown";
        if(extent && extent.length>0){
                 //构造polygon 
                 polygon = '';
                 polygon += extent[0] + ',' + extent[1] + ' ' ;
                 polygon += extent[2] + ',' + extent[1] + ' ' ;
                 polygon += extent[2] + ',' + extent[3] + ' ' ;
                 polygon += extent[0] + ',' + extent[3] + ' ' ;
                 polygon += extent[0] + ',' + extent[1] + ' ' ;
       }
       console.log('polygon',polygon);
       if(polygon){
           queryByPolygon(polygon,'osm_ws:gis_osm_buildings_a_free_1',callbackLastQueryWFSService);
        }
        readyforPick=true;
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);//鼠标右键

    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
        if (readyforPick==false) {
            return;
        }
        var pickedFeature = viewer.scene.pick(movement.position);
        console.log('pickedFeature',pickedFeature);
        if(pickedFeature){
            //判断之前是否有高亮面存在
            if (highlightFace) {
                highlightFace.material = highlightFace.material0;
            }
            if(pickedFeature.id.polygon.material){
                pickedFeature.id.polygon.material0 = pickedFeature.id.polygon.material;
                pickedFeature.id.polygon.material = Cesium.Color.DEEPSKYBLUE.withAlpha(0.8);
                highlightFace = pickedFeature.id.polygon;
                console.log('properties',pickedFeature.id.properties);
                //气泡窗口显示
                var content =
                    "<div>"+
                    "<span>图斑编号:</span><span>"+pickedFeature.id.properties.code+"</span></br>"+
                    "<span>图斑描述::</span><span>"+pickedFeature.id.properties.fclass+"</span></br>"+
                    "</div>";
                $("#infowindow").show();
                $("#infowindow").empty();
                $("#infowindow").append(content);
            }
        }
        else
        {
            if (highlightFace) {
                highlightFace.material = highlightFace.material0;
            }
            $("#infowindow").hide();
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
 }

 function drawShape(positionData) {
    let shape;
    if (drawingMode === "rectangle") 
    {
       
    } 
    else if (drawingMode === "polygon") 
    {
        shape = viewer.entities.add({
        polygon: {
            hierarchy: positionData,
            material: new Cesium.ColorMaterialProperty(
            Cesium.Color.RED.withAlpha(0.7)
            ),
            },
        }); 
    }
    return shape;
}
function createPoint(worldPosition) {
    const point = viewer.entities.add({
        position: worldPosition,
        point: {
        color: Cesium.Color.RED,
        pixelSize: 5,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
    });
    return point;
}
     
/*空间查询图层
*@method queryByPolygon
*@param polygon 空间范围
*@param typeName 图层名称
*@return null
*/
function queryByPolygon(polygon, typeName, callback){
    var filter =
        '<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml">';
        /*filter += '<And>';*/
        filter += '<Intersects>';
        filter += '<PropertyName>the_geom</PropertyName>';
        filter += '<gml:Polygon>';
        filter += '<gml:outerBoundaryIs>';
        filter += '<gml:LinearRing>';
        filter += '<gml:coordinates>' + polygon + '</gml:coordinates>';
        filter += '</gml:LinearRing>';
        filter += '</gml:outerBoundaryIs>';
        filter += '</gml:Polygon>';
        filter += '</Intersects>';
        /*filter += '<PropertyIsLike wildCard="*" singleChar="#" escapeChar="!">';
        filter += '<PropertyName>map_num</PropertyName>';
        filter += '<Literal>*201911_440114*</Literal>';
        filter += '</PropertyIsLike>'; */
        /*filter += '</And>';*/
        filter += '</Filter>';
        var urlString = geoserverUrl + '/ows';
        var param = {
            service: 'WFS',
            version: '1.0.0',
            request: 'GetFeature',
            typeName: typeName,
            outputFormat: 'application/json',
            filter: filter
        };
    var geojsonUrl = urlString + getParamString(param, urlString);
    $.ajax({
            url: geojsonUrl,
            async: true,
            type:'GET',
            dataType: 'json',
            success(result) {
                callback(result);
            },
            error(err) {
                console.log(err);
        }
    })
}

function getParamString(obj, existingUrl, uppercase){
    var params = [];
    for (var i in obj) {
        params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
    }
    return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');    
}
/*
* 图层空间查询回调函数
*/
function callbackLastQueryWFSService(data){
    console.log('data',data);
    if(data && data.features.length>0){
        clearGeojsonLayer();
        loadGeojsonLayer(data);  
    }
}
/*
 * 绘制图形函数
 */
function loadGeojsonLayer(geojson){
    var promise = Cesium.GeoJsonDataSource.load(geojson,geoJsonStyle);
    promise.then(function(dataSource) {
            viewer.dataSources.add(dataSource);
            //viewer.zoomTo(dataSource);
        }).otherwise(function(error){
        //Display any errrors encountered while loading.
        window.alert(error);
    });
}
/*
* 清空绘制图形函数
*/
function clearGeojsonLayer(){
    viewer.dataSources.removeAll();
}

function getExtentByPoints(points) {
    if (points) {
            // 指定世界范围
            let lonMin = 180;
            let lonMax = -180;
            let latMin = 90;
            let latMax = -180;
            points.forEach(function (point) {
                const longitude = point[0];
                const latitude = point[1];
                // 计算边界
                lonMin = longitude < lonMin ? longitude : lonMin;
                latMin = latitude < latMin ? latitude : latMin;
                lonMax = longitude > lonMax ? longitude : lonMax;
                latMax = latitude > latMax ? latitude : latMax;
            });
            const xRange = lonMax - lonMin ? lonMax - lonMin : 1;
            const yRange = latMax - latMin ? latMax - latMin : 1;
            // 返回数据
            return [lonMin - xRange / 10, latMin - yRange / 10, lonMax + xRange / 10, latMax + yRange / 10];
        }
        return [-180,-90,180,90];
    }
/**
* @todo 弧度坐标转经纬度坐标
* @param {Cartographic} cartographic - 弧度坐标
* @return {Object} - {longitude: x, latitude: y, height: h} - 返回经纬度
*/
function cartographicToDegrees(cartographic) {
    const result = {};
    result.longitude = Cesium.Math.toDegrees(cartographic.longitude);
    result.latitude = Cesium.Math.toDegrees(cartographic.latitude);
    if (cartographic.height > 0) {
        result.height = cartographic.height;
    }
    return result;
}

/**
 * @todo 获取 Cartesian3 四至范围
 * @param {Cartesian3} cartesian3s - 世界坐标对象
 * @return {*[]}
 * */
function getExtentByCartesian3(cartesian3s) {
    if(cartesian3s instanceof Array && cartesian3s.length>0){
        const points = [];
        for (let i = 0; i < cartesian3s.length; i++) {
            const cartesian3 = cartesian3s[i];
            // 将 cartesian3 转为经纬度数组               
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
            const point = cartographicToDegrees(cartographic);
            points.push([point.longitude,point.latitude]);
        }
         return getExtentByPoints(points);
    }
}

    
//移除临时绘制图像.
function terminateShape() {
    activeShapePoints.pop();
    // drawShape(activeShapePoints);
    viewer.entities.remove(floatingPoint);
    viewer.entities.remove(activeShape);
    floatingPoint = undefined;
    activeShape = undefined;
    activeShapePoints = [];
}

function clearMap(){
    clearGeojsonLayer();
    readyforPick=false;
    activeShapePoints = [];
    if (handler) {
        handler.destroy();
        handler = null;
    }
}